﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;

public class HttpHostService : BackgroundService
{
    HttpListener listerner;
    public HttpHostService()
    {
        listerner = new HttpListener();
    }
    
    public override Task StartAsync(CancellationToken cancellationToken)
    {
        try
        {
            listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            var url = "http://*:666/";
            Console.WriteLine("URL连接" + url);
            listerner.Prefixes.Add(url);
            listerner.Start();
        }
        catch (Exception ex)
        {
            Console.WriteLine("端口监听打开失败：" + ex.ToString());
        }
        return base.StartAsync(cancellationToken);
    }
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Task.Run(() =>
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                HttpListenerContext ctx = listerner.GetContext();//等待请求
                Task.Run(() =>
                {
                    Callback(ctx);
                });
            }
        });
        return Task.CompletedTask;
    }
    public override Task StopAsync(CancellationToken cancellationToken)
    {
        try
        {
            listerner.Close();
            Console.WriteLine("停止监听666端口");
        }
        catch (Exception e)
        {
            Console.WriteLine("停止监听666端口失败" + e.ToString());
        }
        return base.StopAsync(cancellationToken);
    }
    private void Callback(HttpListenerContext ctx)
    {

        Stream stream = ctx.Request.InputStream;
        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
        var message = reader.ReadToEnd();
        using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream, Encoding.UTF8))
        {
            writer.Write(message);
            writer.Close();
            ctx.Response.Close();
        }
    }
}